package com.gsk.europepharma.salesReport.struts.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Query;
import org.hibernate.Session;

import com.gsk.europepharma.salesReport.hibernate.dao.tbSpBoSRAdmPdtDAO;
import com.gsk.europepharma.salesReport.hibernate.dao.tbSpBoSRSectoDAO;

public class ParametrageOrigine extends Action {
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		HttpSession sessionObject = request.getSession();
		
//		String cs_adm_rgpt_string = request.getParameter("cs_adm_rgpt"); 
//		Integer cs_adm_rgpt = Integer.parseInt(cs_adm_rgpt_string);
		
		int cs_adm_pdt = Integer.parseInt(sessionObject.getAttribute("cs_adm_pdt").toString());
		
		tbSpBoSRAdmPdtDAO admPdtDao = new tbSpBoSRAdmPdtDAO();
		Session session = admPdtDao.getSession();
		Query req = session.getNamedQuery(admPdtDao.QUERY_ADM_ORIGINE);
		req.setInteger("cs_adm_pdt", cs_adm_pdt);
//		req.setInteger("cs_adm_rgpt", cs_adm_rgpt);
		ArrayList result = new ArrayList(req.list());
		
		JSONArray origines = new JSONArray();
		
		Iterator iter = result.iterator();
		while (iter.hasNext()) {
			Object[] tmp = (Object[]) iter.next();
			JSONObject origine = new JSONObject();
			origine.put("marche", tmp[0].toString());
			origine.put("origine", tmp[1].toString());
			origine.put("cs_prod_hier", tmp[2].toString());
			origines.add(origine);
		}
		
		// Valeurs envoyees dans l'action 
		HashMap hm = new HashMap();
        hm.put("origines", origines);
        
        JSONObject json = JSONObject.fromObject(hm);

        response.addHeader("Content-Type", "application/json");
        response.getOutputStream().write(json.toString().getBytes("UTF-8"));
        response.getOutputStream().flush();

		return null;
	}

}
